<template>
  <div id="Header">
    <!-- 内容主体 -->
    <div class="content_reg">
      <div class="header">
        <h1>注册学校账号</h1>
      </div>
      <el-form
        label-width="120px"
        size="large"
        ref="reg_data_ref"
        :model="reg_data"
        :rules="reg_data_rules"
      >
        <div class="block-container">
          <h2>学校信息</h2>
          <div class="form-container">

            <el-form-item
              label="学校类型"
              prop="institutionType"
            >
              <el-select
                v-model="reg_data.institutionType"
                placeholder="选择类型"
              >
                <el-option
                  v-for="item in type_data"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="单位名称"
              prop="unitName"
            >
              <el-input
                v-model="reg_data.unitName"
                placeholder="请输入单位名称"
              />
            </el-form-item>
            <el-form-item
              label="证件执照"
              prop="licenseImg"
            >
              <UploadImage v-model="reg_data.licenseImg" />
              <el-text
                type="info"
                size="small"
                style="line-height:22px"
              >上传单位相关证件执照（如营业执照、办学许可证）只能上传 JPG/PNG 文件，且不超过 5
                MB</el-text>
            </el-form-item>
            <el-form-item
              label="负责人姓名"
              prop="userName"
            >
              <el-input
                v-model="reg_data.userName"
                placeholder="请输入负责人姓名"
              />
            </el-form-item>
            <el-form-item
              label="手机号码"
              prop="phone"
              style="display: flex;"
              v-if="false"
            >
              <el-input
                @change="changePhone"
                v-model="reg_data.phone"
                placeholder="请输入手机号码"
              />
              <el-button
                plain
                class="ipn_btn"
                @click="handleCoundDown(reg_data.phone)"
                :disabled="disabled"
              >{{ btnText }}
              </el-button>
            </el-form-item>
            <el-form-item
              label="手机号码"
              prop="phone"
            >
              <PhoneSendCode v-model="reg_data.phone" />
            </el-form-item>

            <el-form-item
              label="手机验证码"
              prop="phoneCode"
            >
              <el-input
                v-model="reg_data.phoneCode"
                placeholder="请输入手机验证码"
              />
            </el-form-item>

            <el-form-item
              label="登录密码"
              prop="password"
            >
              <el-input
                v-model="reg_data.password"
                type="password"
                placeholder="请输入登录密码"
              />
            </el-form-item>
            <el-form-item
              label="地址"
              prop="address"
            >
              <el-input
                v-model="reg_data.address"
                placeholder="请填写机构邮寄地址"
                class="content_input"
                v-model.trim="inputValueTrim"
              />
            </el-form-item>
            <el-form-item
              label="联系邮箱"
              prop="email"
            >
              <el-input
                v-model="reg_data.email"
                placeholder="请输入联系邮箱"
              />
            </el-form-item>
            <el-form-item
              label="注册邀请码"
              prop="channel"
            >
              <el-input
                v-model="reg_data.channel"
                placeholder="请输入注册邀请码"
              />
            </el-form-item>
          </div>
        </div>
        <div class="block-container">
          <h2>所选地区</h2>
          <div class="form-container">
            <el-form-item
              label="所选地区"
              prop="county"
            >
              <ProvinceSelect
                v-model:economize="reg_data.economize"
                v-model:market="reg_data.market"
                v-model:county="reg_data.county"
                :showCounty="true"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                :loading="reg_loading"
                @click="handleReg"
              >立即注册</el-button>
              <el-button @click="handleJumpLoginPage">前往登录</el-button>
            </el-form-item>
            <!-- <el-form-item>
              <el-button
                type="primary"
                @click="handleTestCode"
              >测试图形验证码</el-button>
            </el-form-item> -->
          </div>
        </div>
      </el-form>
    </div>
    <!-- 验证码弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogText"
      width="20%"
      :before-close="handleClose"
    >
      <span>欢迎参与AI Will综合素养挑战赛，
        您的动态验证为【<b>{{ codePhone }}</b>】，
        非本人操作请忽略，感谢您为科创事业添砖加瓦！
      </span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogVisible = false"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script  setup>
import { useRouter, useRoute } from "vue-router";
import { ref, onMounted } from "vue"
import { useUserStore } from "@/store/user";
import { ElMessage } from "element-plus"
import { RegApi } from "@/api/user"
import { sendCode } from '@/api/index.js'
import UploadImage from "@/components/upload-image/index.vue"
import ProvinceSelect from "@/components/province-select/index.vue"
import { GetCodeTestApi } from "@/api";
import PhoneSendCode from "@/components/phone-send-code/index.vue"

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const type_data = [
  {
    label: "学校",
    value: "school",
  },
  {
    label: "机构",
    value: "institution",
  },
  {
    label: "团队",
    value: "team",
  }, {
    label: "其他",
    value: "other",
  }
];
const checkPhone = (rule, value, callback) => {
  const phoneReg = /^1[3|4|5|6|7|8|9][0-9]{9}$/
  if (!value) {
    callback(new Error('手机号码不能为空'))
  }
  if (phoneReg.test(value)) {
    callback()
  } else {
    callback(new Error('手机号码格式错误'))
  }
}
const reg_data_ref = ref();
const reg_data_rules = ref({
  institutionType: [
    {
      type: 'string',
      required: true,
      message: '请选择学校类型',
      trigger: 'blur',
    }
  ],
  unitName: [
    {
      type: 'string',
      required: true,
      message: '请输入单位名称',
      trigger: 'blur',
    }
  ],
  licenseImg: [
    {
      type: 'string',
      required: true,
      message: '请上传证件执照',
      trigger: 'blur',
    }
  ],
  userName: [
    {
      type: 'string',
      required: true,
      message: '请输入负责人姓名',
      trigger: 'blur',
    }
  ],

  phone: [
    {
      required: true,
      validator: checkPhone,

    }
  ],
  password: [
    {
      type: 'string',
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    }
  ],
  channel: [
    {
      type: 'string',
      required: true,
      message: '请输入邀请码',
      trigger: 'blur',
    }
  ],
  email: [
    {
      type: 'string',
      required: true,
      message: '请输入联系邮箱',
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        // 使用正则表达式验证邮箱格式
        const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
        if (emailPattern.test(value)) {
          // 邮箱格式合法，通过校验
          callback();
        } else {
          // 邮箱格式不合法，校验失败，显示提示信息
          callback(new Error('联系邮箱格式不正确'));
        }
      },
      trigger: 'blur',
    },
  ],
  county: [
    {
      required: true,
      message: '请选择地区',
      trigger: 'blur',
    }
  ],
  //   code: [
  //     {
  //       type: 'string',
  //       required: true,
  //       message: '请输入验证码',
  //       trigger: 'blur',
  //     }
  //   ],
  phoneCode: [
    {
      type: 'string',
      required: true,
      message: '请输入手机验证码',
      trigger: 'blur',
    }
  ],
  address: [
    {
      type: 'string',
      required: true,
      message: '请输入地址',
      trigger: 'blur',

    },
    {
      min: 2, max: 120, message: '地址请输入 2-120 个字符',
      trigger: 'blur'
    },
  ],
});


/**
 * 跳转到注册页
 */
const handleJumpLoginPage = () => {
  router.push("/auth/login");
};
/**
 * 登录数据
 */
const reg_data = ref({
  "institutionType": "school",   //机构类型包括  学校:school  机构:institution 团队:team  其他:other
  "unitName": "",   //单位名称
  "licenseImg": "",  //营业执照
  "userName": "",   //姓名
  "phone": "",   //手机号
  "password": "",   //密码
  "channel": "",  //激活码  机构只能填组委会
  "economize": null,   //省id
  "market": null,   //市id
  "county": null, //县id
  "email": "", // 联系邮箱
  "code": "", //验证码
  "phoneCode": "", // 手机验证码
  "address": "",
});

/**
 * 注册状态
 */
const reg_loading = ref(false)
const handleReg = () => {
  reg_data_ref.value.validate(async (v) => {
    if (!v) {
      return;
    }
    reg_loading.value = true;
    let res = await RegApi(reg_data.value)
    if (!res.success) {
      ElMessage.error(res.message)

    } else {
      router.push("/auth/login");
      ElMessage.success(res.message)
    }
    reg_loading.value = false;
  });
}

// 获取验证码
const dialogVisible = ref(false)
const dialogText = ref('手机验证码(测试阶段-流程使用) ')
const codePhone = ref('')
const handleSendCode = async (phone) => {
  let res = await sendCode({ phone })

  if (res.success) {
    dialogVisible.value = true
    codePhone.value = res.entity
    ElMessage.success(res.message)
  } else {
    ElMessage.error(res.message)
  }
}


// 60秒验证码
const btnText = ref('获取验证码')
const countdown = ref(60)
const disabled = ref(true)
const handleCoundDown = (phone) => {

  if (reg_data.value.code == '') {
    ElMessage.error('请填写验证码')
    return;
  }
  if (disabled.value) {
    return; // 如果按钮已禁用，则不执行任何操作
  }

  handleSendCode(phone)
  let timer = setInterval(() => {
    if (countdown.value <= 0) {
      disabled.value = false
      btnText.value = '获取验证码'
      clearInterval(timer)
      countdown.value = 60
    } else {
      btnText.value = countdown.value + 's 后重试'
      countdown.value--
      disabled.value = true
    }
  }, 1000)
}

// 必须判断成功后才可以点击获取验证码
const changePhone = () => {
  reg_data_ref.value.validate(async (valid, roles) => {
    if (!roles.phone) {
      disabled.value = false;
    } else {
      disabled.value = true;
    }
  });
}


/**
 * onMounted
 */
onMounted(() => {
  reg_data.value.channel = route.query.channel ?? "";
})
</script>

<style lang="scss" scoped>
#Header {
  height: 100vh;
  width: 100%;
  overflow-y: auto;
  //   background: #8473f724;
  background-image: url('@/assets/images/login_bgc.png');
  padding-top: 120px;
  padding-bottom: 32px;
  box-sizing: border-box;

  .content_reg {
    display: flex;
    flex-direction: column;
    width: 740px;
    border-radius: 16px;
    background: #fff;
    margin: 0 auto;
    box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.05);
    padding: 20px;

    .block-container {
      margin-top: 32px;

      .form-container {
        width: 512px;
        padding-top: 16px;
      }
    }
  }
}

:deep(.el-input-group__append) {
  padding: 0;
  cursor: pointer;
  box-sizing: border-box;
}

.code-image {
  height: 100% !important;
  cursor: pointer;
  text-align: center;
}
.ipn_btn {
  position: absolute;
  right: 0;
}
</style>